# coding=utf-8
import os
import time

import allure
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from homework_web_po.util.logger import logger


class BasePage:

    def __init__(self,driver:WebDriver=None):
        if driver is None:
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(10)
            self.driver.maximize_window()
        else:
            self.driver = driver


    def open_url(self,url):
        self.driver.get(url)


    # 查找元素
    def find_ele(self,by,locator):
        ele = self.driver.find_element(by,locator)
        return ele


    def find_eles(self,by,locator):
        eles = self.driver.find_elements(by,locator)
        return eles


    # 点击
    def click(self,by,locator):
        try:
            ele = self.find_ele(by,locator)
            ele.click()
            self.save_page_source()
            self.screen_image()
        except Exception as e:
            logger.info(f"点击{locator}失败,{e}")

    # 输入文本
    def input(self, by, locator,text):
        ele = self.find_ele(by, locator)
        ele.clear()
        ele.send_keys(text)

    def quit(self):
        self.driver.quit()

    def wait_locate(self, by, locate, timeout=10):
        ele = WebDriverWait(self.driver, timeout).until(
            expected_conditions.visibility_of_element_located((by, locate)))
        return ele

    def get_path(self, path_name):
        '''
        获取绝对路径
        :param path_name: 目录名称
        :return: 目录绝对路径
        '''
        # 获取当前工具文件所在的路径
        root_path = os.path.dirname(os.path.abspath(__file__))
        # 拼接当前要输出日志的路径
        dir_path = os.sep.join([root_path, '..', f'/{path_name}'])
        return dir_path


    def screen_image(self):
        '''
        截图
        :return: 图片保存路径
        '''
        # 截图命名
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        image_name = f"{now_time}.png"
        # 拼接截图保存路径
        image_path = f"{self.get_path('image')}/{image_name}"
        logger.info(f"截图保存路径为 {image_path}")
        # 截图
        self.driver.save_screenshot(image_path)
        allure.attach.file(image_path, name='image_name', attachment_type=allure.attachment_type.PNG)
        return image_path


    def save_page_source(self):
        '''
        保存页面源码
        :return: 页面源码保存路径
        '''
        # 文件命名
        now_time = time.strftime('%Y_%m_%d_%H_%M_%S')
        pagesource_name = f"{now_time}_pagesource.html"
        # 拼接文件保存路径
        # windows f"{self.get_path('pagesource')}\\{pagesource_name}"
        pagesource_path = f"{self.get_path('pagesource')}/{pagesource_name}"
        logger.info(f"页面源码文件保存路径为 {pagesource_path}")
        # 保存 page source
        with open(pagesource_path, "w", encoding="utf-8") as f:
            f.write(self.driver.page_source)
        return pagesource_path



